package org.mineground;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.entity.Player;

/**
 * @file Utilities.java (18.02.2012)
 *
 * @author Daniel Koenen
 *
 */
public class Utilities {
    public static Date addSeconds(Date expireDate, int value, char interval) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(expireDate);

        calendar.add((interval == 'h') ? (Calendar.HOUR) : (Calendar.DATE), value);
        return calendar.getTime();
    }
    
    public static boolean isNumeric(String parsedInt) {
        try {
            Integer.parseInt(parsedInt);
        } 
        
        catch (Exception exception) {
            return false;
        }

        return true;
    }
    
    public static String longToIp(long ipAddress) {
        return ((ipAddress >> 24 ) & 0xFF) + "." + ((ipAddress >> 16 ) & 0xFF) + "." + ((ipAddress >> 8 ) & 0xFF) + "." + (ipAddress & 0xFF);
    }

    /**
     * Converts a string representation of an IP address to a long.
     *
     * @param addr The string representation of the IP address to convert.
     * @return The IP as a long.
     */
    public static long ipToLong(String addr) {
        String[] addrArray = addr.split("\\.");
        long num = 0;

        for (int i = 0; i < addrArray.length; i++) {
            int power = 3 - i;
            num += ((Integer.parseInt(addrArray[i]) % 256 * Math.pow(256, power)));
        }

        return num;
    }

    public static double getThreadCPUUsage() {
        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        return (threadMXBean.getCurrentThreadCpuTime() - threadMXBean.getCurrentThreadUserTime())
                / (threadMXBean.getCurrentThreadCpuTime() / 100);
    }

    public static void sendMessageToAll(String message) {
        Main.getInstance().getServer().broadcastMessage(message);
    }

    public static void sendAdminMessage(String message) {
        Player[] onlinePlayers = Main.getInstance().getServer().getOnlinePlayers();

        for (Player onlinePlayer : onlinePlayers) {
            if (onlinePlayer.hasPermission(PermissionNodes.PERMISSION_READ_ADMIN_CHAT)) {
                onlinePlayer.sendMessage(message);
            }
        }
    }
    
    public static int countOnlineAdmins() {
        Player[] onlinePlayers  = Main.getInstance().getServer().getOnlinePlayers();
        int adminCounter = 0;

        for (Player onlinePlayer : onlinePlayers) {
            if (onlinePlayer.hasPermission(PermissionNodes.PERMISSION_READ_ADMIN_CHAT)) {
                adminCounter++;
            }
        }
        
        return adminCounter;
    }

    public static String fixName(Player player) {
        String playerName = player.getDisplayName();
        Map<String, String> replacements = new HashMap<String, String>();

        char paragraph = 167;
        char ircColorChar = 3;

        replacements.put(paragraph + "0", ircColorChar + "1");
        replacements.put(paragraph + "1", ircColorChar + "12");
        replacements.put(paragraph + "2", ircColorChar + "3");
        replacements.put(paragraph + "3", ircColorChar + "10");
        replacements.put(paragraph + "4", ircColorChar + "4");
        replacements.put(paragraph + "5", ircColorChar + "13");
        replacements.put(paragraph + "6", ircColorChar + "8");
        replacements.put(paragraph + "7", ircColorChar + "15");
        replacements.put(paragraph + "8", ircColorChar + "14");
        replacements.put(paragraph + "9", ircColorChar + "12");
        replacements.put(paragraph + "a", ircColorChar + "9");
        replacements.put(paragraph + "b", ircColorChar + "11");
        replacements.put(paragraph + "c", ircColorChar + "4");
        replacements.put(paragraph + "d", ircColorChar + "13");
        replacements.put(paragraph + "e", ircColorChar + "18");
        replacements.put(paragraph + "f", ircColorChar + "0");

        if (playerName.length() == 0) {
            System.out.println("Error: playerName.length() = 0");
            return "Player";
        }

        if (playerName.contains("" + paragraph)) {
            for (Map.Entry<String, String> entry : replacements.entrySet()) {
                playerName = playerName.replace(entry.getKey(), entry.getValue());
            }
        }

        return playerName;
    }

    public static String formatTime(long seconds) {
        long days = 0;
        long hours = 0;
        long minutes = 0;
        long secs;
        String time;

        while (seconds >= 60) {
            minutes++;
            seconds -= 60;
        }

        secs = seconds;

        while (minutes >= 60) {
            hours++;
            minutes -= 60;
        }

        while (hours >= 24) {
            days++;
            hours -= 24;
        }

        if (days == 0 && hours == 0 && minutes == 0) {
            time = secs + " seconds";
        } else if (days == 0 && hours == 0) {
            time = minutes + " minutes and " + secs + " seconds";
        } else if (days == 0) {
            time = hours + " hours, " + minutes + " minutes and " + secs + " seconds";
        } else {
            time = days + " days, " + hours + " hours, " + minutes + " minutes and " + secs + " seconds";
        }

        return time;
    }

    public static long daysBetween(Date d1, Date d2) {
        return (d2.getTime() - d1.getTime() + 60 * 60 * 1000L) / (60 * 60 * 1000L * 24);
    }

    public static String getOnlinePlayers() {
        StringBuilder format = new StringBuilder();

        format.append(Main.getInstance().getServer().getOnlinePlayers().length);
        format.append("/");
        format.append(Main.getInstance().getServer().getMaxPlayers());
        format.append(" online players.");

        return format.toString();
    }
}
